package com.example.ordersystem.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.ordersystem.pojo.Order;

import java.util.ArrayList;

/*
 * 数据库管理类
 * 用于保存用户已经结算的订单，将数据存储在数据库中，用于在历史订单页面查看
 */
public class MyDBOpenHelper extends SQLiteOpenHelper {

    public MyDBOpenHelper(Context context) {
        super(context, "my.db", null, 1);
    }

    @Override
    //数据库第一次创建时被调用，并创建用户对应的历史订单表
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS user_order(" +
                "oid INTEGER PRIMARY KEY AUTOINCREMENT," +
                "foodName varchar(40)," +
                "foodMessage varchar(40)," +
                "foodPrice INTEGER," +
                "foodNum INTEGER," +
                "storeName varchar(40)," +
                "userName varchar(40)," +
                "otime varchar(50))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public ArrayList<Order> query(SQLiteDatabase db, String userName) {
        ArrayList<Order> list = new ArrayList<Order>();
        Cursor cursor = db.rawQuery("SELECT * FROM user_order WHERE userName = ?", new String[]{userName});
        while (cursor.moveToNext()) {
            String foodName = cursor.getString(cursor.getColumnIndex("foodName"));
            String foodMessage = cursor.getString(cursor.getColumnIndex("foodMessage"));
            int foodPrice = cursor.getInt(cursor.getColumnIndex("foodPrice"));
            int foodNum = cursor.getInt(cursor.getColumnIndex("foodNum"));
            String storeName = cursor.getString(cursor.getColumnIndex("storeName"));
            String userName1 = cursor.getString(cursor.getColumnIndex("userName"));
            String otime = cursor.getString(cursor.getColumnIndex("otime"));
            list.add(new Order(foodName, foodMessage, foodPrice, foodNum, storeName, userName1, otime));
        }
        return list;
    }
}